package com.dd.cloud.user.service.phar.pharservice;

import cn.hutool.core.codec.Base64;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.dd.cloud.common.constants.PharConstants;
import com.dd.cloud.common.constants.PresConstants;
import com.dd.cloud.common.enums.ZkExceptionEnum;
import com.dd.cloud.common.exception.ZekeException;
import com.dd.cloud.common.interceptor.UserInterceptor;
import com.dd.cloud.common.utils.*;
import com.dd.cloud.common.vo.LoginInfo;
import com.dd.cloud.user.DTO.CallbackPresStatusReq;
import com.dd.cloud.user.DTO.CancelPresReq;
import com.dd.cloud.user.DTO.CommonParamReq;
import com.dd.cloud.user.DTO.km.*;
import com.dd.cloud.user.entity.doctor.PatientMedCard;
import com.dd.cloud.user.entity.order.OrderPay;
import com.dd.cloud.user.entity.phar.Pharmacy;
import com.dd.cloud.user.entity.phar.PharmacyDocking;
import com.dd.cloud.user.entity.pres.PresKmDetail;
import com.dd.cloud.user.entity.pres.PresKmPharRoam;
import com.dd.cloud.user.entity.pres.PresPrescription;
import com.dd.cloud.user.entity.pres.PresPretrialDrugs;
import com.dd.cloud.user.enums.ExceptionEnum;
import com.dd.cloud.user.req.pres.PresCreateKmReq;
import com.dd.cloud.user.req.pres.PresCreateReq;
import com.dd.cloud.user.req.pres.PresPatientAddrReq;
import com.dd.cloud.user.service.doctor.IDoctorEquityService;
import com.dd.cloud.user.service.doctor.IDoctorOrderIncomeDetailService;
import com.dd.cloud.user.service.log.ILogErrorService;
import com.dd.cloud.user.service.order.IOrderPayService;
import com.dd.cloud.user.service.phar.IPharmacyDockingService;
import com.dd.cloud.user.service.phar.IPharmacyService;
import com.dd.cloud.user.service.pres.IPresKmDetailService;
import com.dd.cloud.user.service.pres.IPresKmPharRoamService;
import com.dd.cloud.user.service.pres.IPresPrescriptionService;
import com.dd.cloud.user.service.pres.IPresPretrialDrugsService;
import com.dd.cloud.user.service.sms.ISmsService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.net.URLEncoder;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

/**
 * 康美药房服务类
 *
 * @author Lx
 * @version 1.0
 */
@Slf4j
@Service
public class KmPharService extends PharAbstractService {
    @Autowired
    private IPresKmDetailService presKmDetailService;
    @Autowired
    private IOrderPayService orderPayService;
    @Autowired
    private ILogErrorService logErrorService;
    @Autowired
    private IPresPrescriptionService presPrescriptionService;
    @Autowired
    private IPharmacyService pharmacyService;
    @Autowired
    private IPharmacyDockingService pharmacyDockingService;
    @Autowired
    private IPresPretrialDrugsService presPretrialDrugsService;
    @Autowired
    private IPresKmPharRoamService presKmPharRoamService;
    @Autowired
    private IDoctorOrderIncomeDetailService doctorOrderIncomeDetailService;
    @Autowired
    private ISmsService smsService;

    @Autowired
    private IDoctorEquityService doctorEquityService;

    /**
     * 添加药房的处方详情
     *
     * @param req
     * @param medCard
     */
    @Override
    public void addPresDetail(PresCreateReq req, PatientMedCard medCard) {
        LoginInfo loginInfo = UserInterceptor.getLoginUserInfo().get();
        PresCreateKmReq kmReq = (PresCreateKmReq) req;
        PresKmDetail detail = new PresKmDetail();
        BeanUtils.copyProperties(kmReq, detail);
        BeanUtils.copyProperties(medCard, detail);
        detail.setOrderTime(LocalDateTime.now().format(DateUtils.DTF_YMD_HMS));
        detail.setRegNum(req.getTencode());
        detail.setOtherPresNum(req.getTencode());
        detail.setUserName(medCard.getName());
        detail.setIsPregnant(medCard.getPregnant());
        detail.setGender("男".equals(medCard.getSex()) ? 1 : 0);
        detail.setAge(CalendarUtil.getAge(medCard.getBirthDate()));
        detail.setDoctor(loginInfo.getName());
        detail.setTel(medCard.getMobileNumber());
        detail.setPerPackNum(req.getDoseNum());
        detail.setPerPackDose(req.getPackagenum());
        detail.setMedicationMethods(kmReq.getMedicationMethods() == null || "无".equals(kmReq.getMedicationMethods()) ? "" : kmReq.getMedicationMethods());
        detail.setMoney(BigDecimalUtils.divide(BigDecimal.valueOf(req.getMoney()), BigDecimal.valueOf(100)));
        detail.setCreateDate(LocalDateTime.now());
        boolean i = presKmDetailService.saveOrUpdate(detail);
        if (!i) {
            throw new ZekeException(ExceptionEnum.PRES_CREATE_ERROR, "处方信息保存失败");
        }
    }

    @Override
    public boolean sendPresToPhar(OrderPay pay) {
        boolean succ = false;
        log.info("发送处方到康美药房");
        if (StringUtils.isBlank(pay.getServerNo())) {
            //没有处方编码 数据异常, 退款
            orderPayService.refund(pay.getOrderNo(), 0);
            logErrorService.presBackLog("没有处方编码-数据异常, 退款", "处方发送到康美药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        PresPrescription presPrescription = presPrescriptionService.getById(pay.getServerNo());
        if (presPrescription == null) {
            //处方为空, 数据异常, 退款
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("处方为空-数据异常", "处方发送到康美药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        if (presPrescription.getStatus() == PresConstants.PresStatus.SENDPHARM) {
            //处方已发送到药房, 此为重复回调
            log.info("处方已发送到药房, 此为重复回调");
            return succ;
        }
        PresKmDetail kmDetail = presKmDetailService.getById(pay.getServerNo());
        if (kmDetail == null) {
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("获取发送给药房的详细数据失败", "处方发送到康美药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        Pharmacy pharmacy = pharmacyService.getById(presPrescription.getPharmId());
        if (pharmacy == null) {
            //药房为空, 数据异常 ,退款
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("药房为空-数据异常", "处方发送到康美药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        QueryWrapper<PharmacyDocking> qd = new QueryWrapper<>();
        qd.lambda().eq(PharmacyDocking::getPharId, pharmacy.getId()).eq(PharmacyDocking::getStatus, PharConstants.DockingStatus.NOMER);
        PharmacyDocking pharmacyDocking = pharmacyDockingService.getOne(qd);
        if (pharmacyDocking == null) {
            //药房为空, 数据异常 ,退款
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("药房对接信息为空-数据异常", "处方发送到康美药房异常", "pharId=" + pharmacy.getId());
            return succ;
        }
        SendPresDataDTO data = new SendPresDataDTO();
        data.setCon_tel(kmDetail.getConTel());
        data.setReg_num(kmDetail.getRegNum());
        data.setAddr_str(kmDetail.getAddrStr());
        data.setOrder_time(kmDetail.getOrderTime());
        data.setConsignee(kmDetail.getConsignee());
        try {
            String param = AESUtil.encrypt(kmDetail.getTencode(), AESUtil.SECRET_KEY);
            param = URLEncoder.encode(param, "UTF-8");
            data.setCallback_url(pharmacyDocking.getPresCallbackUrl() + param);
            data.setLogis_url_callback(pharmacyDocking.getExpressUrl() + param);
        } catch (Exception e) {
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("药房回调信息加密出现异常", "处方发送到康美药房异常", "pharId=" + pharmacy.getId() + ",tencode=" + pay.getServerNo());
            return succ;
        }
        SendPresPrescriptDTO pres = new SendPresPrescriptDTO();
        pres.setAge(kmDetail.getAge().toString());
        pres.setAmount(kmDetail.getAmount().toString());
        pres.setDoctor(kmDetail.getDoctor());
        pres.setGender(kmDetail.getGender());
        pres.setImages(kmDetail.getImages());
        pres.setInvomoney(kmDetail.getInvomoney());
        pres.setPaste_desc_file(kmDetail.getPasteDescFile());
        pres.setIs_invoice(kmDetail.getIsInvoice());
        pres.setIs_pregnant(kmDetail.getIsPregnant());
        pres.setIs_suffering(kmDetail.getIsSuffering());
        pres.setIs_within(kmDetail.getIsWithin());
        pres.setLook_up(kmDetail.getLookUp());
        pres.setMoney(kmDetail.getMoney());
        pres.setOther_pres_num(kmDetail.getOtherPresNum());
        pres.setMedication_methods(kmDetail.getMedicationMethods());
        pres.setPackage_dose(kmDetail.getPackageDose());
        pres.setType(kmDetail.getType());
        pres.setWj_type(kmDetail.getWjType());
        pres.setUser_name(kmDetail.getUserName());
        pres.setPer_pack_num(kmDetail.getPerPackNum());
        pres.setPer_pack_dose(kmDetail.getPerPackDose());
        pres.setTel(kmDetail.getTel());
        pres.setSpecial_instru(kmDetail.getSpecialInstru());
        if (kmDetail.getMedicationInstruction() == null || "无".equals(kmDetail.getMedicationInstruction())) {
            pres.setMedication_instruction("共" + presPrescription.getAllDose() + "剂,每天" + presPrescription.getDayDose() + "剂,每剂" + presPrescription.getDoseNum() + "次,每次" + presPrescription.getDrugDose() + "ml");
        } else {
            pres.setMedication_instruction(kmDetail.getMedicationInstruction() + " 共" + presPrescription.getAllDose() + "剂,每天" + presPrescription.getDayDose() + "剂,每剂" + presPrescription.getDoseNum() + "次,每次" + presPrescription.getDrugDose() + "ml");
        }
        if (pres.getMedication_instruction().length() > 200) {
            pres.setMedication_instruction(pres.getMedication_instruction().substring(0, 200));
        }
        if (kmDetail.getPrescriptRemark() == null || "无".equals(kmDetail.getPrescriptRemark())) {
            if (presPrescription.getAdvice().length() <= 200) {
                pres.setPrescript_remark(presPrescription.getAdvice());
            }
        } else {
            if (presPrescription.getAdvice().length() + kmDetail.getPrescriptRemark().length() > 200) {
                pres.setPrescript_remark(kmDetail.getPrescriptRemark());
            } else {
                pres.setPrescript_remark(kmDetail.getPrescriptRemark() + " " + presPrescription.getAdvice());
            }
        }
        if (pres.getPrescript_remark().length() > 200) {
            pres.setPrescript_remark(pres.getPrescript_remark().substring(0, 200));
        }
        List<SendPresMediciXqDTO> xqList = new ArrayList<>();
        QueryWrapper<PresPretrialDrugs> qw = new QueryWrapper<>();
        qw.lambda().eq(PresPretrialDrugs::getTencode, presPrescription.getTencode()).eq(PresPretrialDrugs::getStatus, PresConstants.PresDrugsStatus.NOMER);
        List<PresPretrialDrugs> drugsList = presPretrialDrugsService.list(qw);
        if (drugsList == null || drugsList.isEmpty()) {
            //没有处方药品, 数据异常, 退款
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("没有处方药品-数据异常", "处方发送到康美药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        for (PresPretrialDrugs drugs : drugsList) {
            SendPresMediciXqDTO xq = new SendPresMediciXqDTO();
            xq.setMedicines(drugs.getHerbName());
            xq.setDose(replace(drugs.getDrugallnum().toString()));
            xq.setUnit(drugs.getUnit());
            xq.setHerb_unit_price(BigDecimalUtils.divide(BigDecimal.valueOf(drugs.getRetailprice()), BigDecimal.valueOf(100), 3).toString());
            xq.setGoods_num(drugs.getDrugnum());
            xq.setDose_that(drugs.getDrugdescription());
            xq.setGoods_norms(drugs.getSpecification());
            xq.setM_usage(drugs.getDecocting());
            xqList.add(xq);
        }
        pres.setMediciXqDTOList(xqList);
        List<SendPresPrescriptDTO> presList = new ArrayList<>(1);
        presList.add(pres);
        data.setPresList(presList);
        data.setPay_status(kmDetail.getPayStatus().toString());
        SendPresBodyDTO body = new SendPresBodyDTO();
        SendPresHeadDTO head = new SendPresHeadDTO("saveOrderInfo");
        head.setCompany_num(pharmacyDocking.getMchId());
        head.generateSign(pharmacyDocking.getEncryptyKey());
        body.setHead(head);
        body.setData(data);
        String soapXml = body.toSoapXml();
        log.info("soapXml:{}", soapXml);
        //发送处方到药房
        String result;
        try {
            log.info("发送url:{}", pharmacyDocking.getServicesUrl());
            result = HttpRequestUtils.postWithXml(pharmacyDocking.getServicesUrl(), soapXml);
            log.info("康美药房返回:{}", result);
            result = result.substring(result.indexOf("<return>") + 8, result.indexOf("</return>"));
            result = Base64.decodeStr(result);
            log.info("处理康美药房返回后的值:{}", result);
        } catch (Exception e) {
            e.printStackTrace();
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("发送处方失败-数据异常", "处方发送到康美药房异常", "tencode=" + pay.getServerNo());
            return succ;
        }
        ResultResDTO resDTO;
        try {
            resDTO = ResultResDTO.toPojo(result);
        } catch (Exception e) {
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("药房返回数据json解析失败", "处方发送到康美药房异常", "res=" + result);
            return succ;
        }
        if (!"0".equals(resDTO.getResultCode())) {
            //接口返回异常 退款
//            orderPayService.refund(pay.getOrderNo(), 0);
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("药房返回状态码异常, 退款", "处方发送到康美药房异常", "msg=" + resDTO.getDescription());
            return succ;
        }
        presPrescription.setStatus(PresConstants.PresStatus.SENDPHARM);
        presPrescription.setUpdateDate(LocalDateTime.now());
        boolean flag = presPrescriptionService.updateById(presPrescription);
        if (!flag) {
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("发送处方到药房成功, 处方更新失败", "处方发送到康美药房异常", "jsonBody=" + presPrescription);
            return succ;
        }
        PresKmDetail update = new PresKmDetail();
        update.setTencode(pay.getServerNo());
        update.setOrderId(resDTO.getOrderInfo().getOrderid());
        flag = presKmDetailService.updateById(update);
        if (!flag) {
            presPrescription.setStatus(PresConstants.PresStatus.SENDPHARMERROR);
            presPrescriptionService.updateById(presPrescription);
            logErrorService.presBackLog("发送处方到药房成功, 康美处方详情更新失败", "处方发送到康美药房异常", "jsonBody=" + presPrescription);
            return succ;
        }
        succ = true;
        return succ;
    }

    public static String replace(String s) {
        if (null != s && s.indexOf(".") > 0) {
            //去掉多余的0
            s = s.replaceAll("0+?$", "");
            //如最后一位是.则去掉
            s = s.replaceAll("[.]$", "");
        }
        return s;
    }

    @Override
    public void cancelPres(CancelPresReq req) {
        PresPrescription presPrescription = presPrescriptionService.getById(req.getTencode());
        if (presPrescription == null) {
            throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, "查询处方失败");
        }
        Pharmacy pharmacy = pharmacyService.getById(presPrescription.getPharmId());
        if (pharmacy == null) {
            throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, "查询药房失败");
        }
        QueryWrapper<PharmacyDocking> qd = new QueryWrapper<>();
        qd.lambda().eq(PharmacyDocking::getPharId, pharmacy.getId()).eq(PharmacyDocking::getStatus, PharConstants.DockingStatus.NOMER);
        PharmacyDocking pharmacyDocking = pharmacyDockingService.getOne(qd);
        if (pharmacyDocking == null) {
            throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, "查询药房信息失败");
        }
        CancelPresBodyDTO bodyDTO = new CancelPresBodyDTO();
        SendPresHeadDTO headDTO = new SendPresHeadDTO("saveCancelOrder");
        headDTO.setCompany_num(pharmacyDocking.getMchId());
        headDTO.generateSign(pharmacyDocking.getEncryptyKey());
        CancelPresBodyDTO.Data data = new CancelPresBodyDTO.Data();
        data.setReason(req.getCancelMsg());
        data.setOper_name(req.getOperName());
        QueryWrapper<PresKmDetail> qw = new QueryWrapper<>();
        qw.lambda().eq(PresKmDetail::getTencode, req.getTencode());
        qw.lambda().select(PresKmDetail::getOrderId);
        PresKmDetail kmDetail = presKmDetailService.getOne(qw);
        data.setOrder_id(kmDetail.getOrderId());
        bodyDTO.setHead(headDTO);
        bodyDTO.setData(data);
        //转soapXml
        String soapXml = bodyDTO.toSoapXml();
        //发送处方到药房
        String result;
        try {
            //发送处方到康美药房
            log.info("发送url:{}", pharmacyDocking.getCancelUrl());
            result = HttpRequestUtils.postWithXml(pharmacyDocking.getCancelUrl(), soapXml);
            log.info("康美药房返回:{},", result);
            result = result.substring(result.indexOf("<return>") + 8, result.indexOf("</return>"));
            result = Base64.decodeStr(result);
            log.info("处理康美药房返回后的值:{}", result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, "调用药房取消处方接口异常");
        }
        ResultResDTO resDTO;
        try {
            resDTO = ResultResDTO.toPojo(result);
        } catch (Exception e) {
            e.printStackTrace();
            throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, "药房接口解析失败,请联系管理员");
        }
        if (!"0".equals(resDTO.getResultCode())) {
            throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, resDTO.getDescription());
        }
        PresPrescription update = new PresPrescription();
        update.setTencode(req.getTencode());
        update.setStatus(PresConstants.PresStatus.CANCEL);
        update.setUpdateDate(LocalDateTime.now());
        boolean flag = presPrescriptionService.updateById(update);
        if (!flag) {
            logErrorService.presBackLog("取消处方康美返回成功,数据修改失败", "取消处方", "tencode=" + presPrescription.getTencode());
            throw new ZekeException(ZkExceptionEnum.CANCEL_PRES_ERROR, "数据修改失败,请联系管理员");
        }
    }

    @Override
    public String presCallback(CallbackPresStatusReq req) {
        log.info("康美药房审核状态回调 参数值:{}", req);
        KmStatusReportReq kmReq = (KmStatusReportReq) req.toStatusPojo();
        boolean flag = kmReq.decrypt();
        if (!flag) {
            return "fail";
        }
        PresPrescription presPrescription = presPrescriptionService.getById(kmReq.getParam());
        if (presPrescription == null) {
            logErrorService.presBackLog("处方编号号不存在", "康美回调处方状态异常", "tencode=" + kmReq.getParam());
            throw new ZekeException(ZkExceptionEnum.PARAMETER_ERROR, "处方编号号不存在");
        }
        int status;
        switch (kmReq.getState()) {
            case PresConstants.KmPresStatus.AUDITSUC:
                status = PresConstants.PresStatus.AUDIT;
                break;
            case PresConstants.KmPresStatus.ADJUSTNO:
                status = PresConstants.PresStatus.AUDITNO;
                break;
            default:
                return "fail";
        }
        if (presPrescription.getStatus().equals(status)) {
            //重复请求
            return "success";
        }
        presPrescription.setStatus(status);
        presPrescription.setUpdateDate(LocalDateTime.now());
        flag = presPrescriptionService.updateById(presPrescription);
        if (!flag) {
            logErrorService.presBackLog("修改处方信息失败", "康美回调处方信息异常", "tencode=" + presPrescription.getTencode());
        }
        QueryWrapper<PresKmPharRoam> qr = new QueryWrapper<>();
        qr.lambda().eq(PresKmPharRoam::getTencode, presPrescription.getTencode()).last("limit 1");
        PresKmPharRoam roam = presKmPharRoamService.getOne(qr);
        if (roam != null) {
            logErrorService.presBackLog("处方流转信息已存在", "康美回调处方信息异常", "tencode=" + presPrescription.getTencode());
            return "success";
        }
        roam = new PresKmPharRoam();
        BeanUtils.copyProperties(kmReq, roam);
        roam.setTencode(presPrescription.getTencode());
        roam.setCreateDate(LocalDateTime.now());
        flag = presKmPharRoamService.save(roam);
        if (!flag) {
            logErrorService.presBackLog("保存处方流转信息失败", "康美回调处方信息异常", "tencode=" + presPrescription.getTencode());
        }
        return "success";
    }

    @Override
    public String expressCallback(CommonParamReq req) {
        log.info("康美药房物流回调 参数值:{}", req);
        KmExpressReportReq kmReq = (KmExpressReportReq) req.toExpressPojo();
        boolean flag = kmReq.decrypt();
        if (!flag) {
            return "fail";
        }
        PresPrescription presPrescription = presPrescriptionService.getById(kmReq.getParam());
        if (presPrescription == null) {
            logErrorService.presBackLog("处方编号号不存在", "康美回调处方状态异常", "tencode=" + kmReq.getParam());
            throw new ZekeException(ZkExceptionEnum.PARAMETER_ERROR, "处方编号号不存在");
        }
        int status;
        LocalDateTime outboundDate = null;
        switch (kmReq.getType()) {
            case PresConstants.KmPresType.OUTBOUND:
                status = PresConstants.PresStatus.DELIVERY;
                outboundDate = LocalDateTime.now();
                presPrescription.setExpressno(kmReq.getWayBillNo());
                presPrescription.setExpresscompany(kmReq.getLogisCompanyName());
                smsService.sendDeliveryPres(presPrescription.getTencode(), presPrescription.getDoctorId(), presPrescription.getName(), kmReq.getWayBillNo(), kmReq.getLogisCompanyName());
                LambdaQueryWrapper<OrderPay> queryWrapper = new LambdaQueryWrapper<>();
                queryWrapper.eq(OrderPay::getServerNo, presPrescription.getTencode()).eq(OrderPay::getStatus, 2);
                OrderPay orderPay = orderPayService.getOne(queryWrapper);
                if (orderPay != null) {
                    doctorEquityService.saveDoctorEquity(orderPay, 2);
                }
                break;
            case PresConstants.KmPresType.SIGNIN:
                status = PresConstants.PresStatus.SUC;
                doctorOrderIncomeDetailService.doctorOrderIncomeEntrySuc(presPrescription.getTencode(), presPrescription.getDoctorId());
                break;
            default:
                return "fail";
        }
        if (presPrescription.getStatus().equals(status)) {
            //重复请求
            return "success";
        }
        presPrescription.setStatus(status);
        presPrescription.setUpdateDate(LocalDateTime.now());
        flag = presPrescriptionService.updateById(presPrescription);
        if (!flag) {
            logErrorService.presBackLog("修改处方信息失败", "康美回调处方信息异常", "tencode=" + kmReq.getParam());
        }
        QueryWrapper<PresKmPharRoam> qr = new QueryWrapper<>();
        qr.lambda().eq(PresKmPharRoam::getTencode, presPrescription.getTencode()).last("limit 1");
        PresKmPharRoam roam = presKmPharRoamService.getOne(qr);
        if (roam != null) {
            BeanUtils.copyProperties(kmReq, roam);
            roam.setOutboundDate(outboundDate);
            roam.setReceivingTime(kmReq.getReceivingTime());
            flag = presKmPharRoamService.updateById(roam);
            if (!flag) {
                logErrorService.presBackLog("修改处方流转信息失败", "康美回调处方信息异常", "tencode=" + kmReq.getParam());
            }
        } else {
            roam = new PresKmPharRoam();
            BeanUtils.copyProperties(kmReq, roam);
            roam.setTencode(presPrescription.getTencode());
            roam.setCreateDate(LocalDateTime.now());
            flag = presKmPharRoamService.save(roam);
            if (!flag) {
                logErrorService.presBackLog("保存处方流转信息失败", "康美回调处方信息异常", "tencode=" + kmReq.getParam());
            }
        }
        return "success";
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePresPatientAddrInfo(PresPatientAddrReq req) {
        UpdateWrapper<PresKmDetail> uw = new UpdateWrapper<>();
        uw.lambda().eq(PresKmDetail::getTencode, req.getTencode());
        uw.lambda().set(PresKmDetail::getConsignee, req.getReceiver());
        uw.lambda().set(PresKmDetail::getConTel, req.getMobileNumber());
        uw.lambda().set(PresKmDetail::getAddrStr, req.getProvince() + "," + req.getCity() + "," + req.getDistrict() + "," + req.getAddr());
        boolean flag = presKmDetailService.update(uw);
        if (!flag) {
            throw new ZekeException(400, "修改处方收货人信息失败");
        }
    }
}
